package com.zdb.service.impl;

import com.zdb.mapper.PerssionMapper;
import com.zdb.mapper.RoleMapper;
import com.zdb.mapper.UserMapper;
import com.zdb.pojo.LoginUser;
import com.zdb.pojo.Permission;
import com.zdb.pojo.Role;
import com.zdb.pojo.User;
import com.zdb.service.AuthenticationService;
import com.zdb.util.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;


@Service
public class AuthenticationServiceImpl implements AuthenticationService {

    private static final Logger log = LoggerFactory.getLogger(AuthenticationServiceImpl.class);
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PerssionMapper perssionMapper;

    @Autowired
    private RoleMapper roleMapper;
    @Override
    public String login(String username, String password) {
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, password);
        try {
            Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
            LoginUser loginUser = (LoginUser)authenticate.getPrincipal();
            log.info("用户信息：{}", loginUser);
            String token = jwtUtil.createToken(loginUser);
            log.info("生成token：{}", token);
            return token;
        } catch (Exception e) {
            log.error("登录失败：{}", e.getMessage());
            return null;
        }
    }

    @Override
    public HashMap<String,Object> getUserInfo() {
        LoginUser loginUser =(LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User user = userMapper.selectById(loginUser.getId());
        List<Permission> permissions = perssionMapper.selectPermissionByUserId(user.getId());
        List<Role> roles = roleMapper.selectRoleByUserId(user.getId());
        HashMap<String,Object> map = new HashMap<>();
        map.put("user",user);
        map.put("permissions",permissions);
        map.put("role",roles);
        return map;
    }
}
